package com.hotel.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hotel.entity.Member;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

/**
 * 会员Mapper接口
 */
@Mapper
public interface MemberMapper extends BaseMapper<Member> {
    
    /**
     * 获取总消费额
     */
    @Select("SELECT SUM(total_consumption) FROM member WHERE status = 1")
    Double getTotalConsumption();
    
    /**
     * 获取总积分
     */
    @Select("SELECT SUM(points) FROM member WHERE status = 1")
    Integer getTotalPoints();
    
    /**
     * 获取会员等级分布
     */
    @Select("SELECT level as name, COUNT(*) as value FROM member WHERE status = 1 GROUP BY level")
    List<Map<String, Object>> getMemberLevelDistribution();
    
    /**
     * 获取会员增长趋势
     */
    List<Map<String, Object>> getMemberGrowthTrend(@Param("type") String type);
    
    /**
     * 根据日期范围统计新增会员
     */
    @Select("SELECT DATE(create_time) as date, COUNT(*) as count " +
            "FROM member " +
            "WHERE create_time >= #{startDate} AND create_time <= #{endDate} " +
            "GROUP BY DATE(create_time) " +
            "ORDER BY date")
    List<Map<String, Object>> getNewMembersByDateRange(@Param("startDate") String startDate, 
                                                        @Param("endDate") String endDate);
    
    /**
     * 获取活跃会员统计
     */
    @Select("SELECT " +
            "  COUNT(CASE WHEN last_visit_time >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as week_active, " +
            "  COUNT(CASE WHEN last_visit_time >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as month_active, " +
            "  COUNT(CASE WHEN last_visit_time >= DATE_SUB(NOW(), INTERVAL 90 DAY) THEN 1 END) as quarter_active " +
            "FROM member WHERE status = 1")
    Map<String, Object> getActiveMemberStats();
    
    /**
     * 获取会员消费排行
     */
    @Select("SELECT name, phone, total_consumption, level " +
            "FROM member " +
            "WHERE status = 1 " +
            "ORDER BY total_consumption DESC " +
            "LIMIT #{limit}")
    List<Map<String, Object>> getTopConsumptionMembers(@Param("limit") int limit);
    
    /**
     * 获取会员积分排行
     */
    @Select("SELECT name, phone, points, level " +
            "FROM member " +
            "WHERE status = 1 " +
            "ORDER BY points DESC " +
            "LIMIT #{limit}")
    List<Map<String, Object>> getTopPointsMembers(@Param("limit") int limit);
    
    /**
     * 统计各等级会员消费情况
     */
    @Select("SELECT " +
            "  level, " +
            "  COUNT(*) as member_count, " +
            "  SUM(total_consumption) as total_consumption, " +
            "  AVG(total_consumption) as avg_consumption " +
            "FROM member " +
            "WHERE status = 1 " +
            "GROUP BY level")
    List<Map<String, Object>> getLevelConsumptionStats();
}